package com.freecloud.javabasics.algorithm.random;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多线程0-100之间出现的概率
 *
 * @Author: maomao
 * @Date: 2021/8/20 5:24 下午
 */
public class RandomNumberThread {

    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMap<Integer, AtomicInteger> allMap = initMap();
        /** 固定线程数的线程池 */
        ExecutorService service = Executors.newFixedThreadPool(1000);

        for (int i = 0; i < 100; i++) {
            service.execute(new TestTask(allMap));
        }
        service.shutdown();

        Integer sum = 0;

        allMap.keySet();

        List<Integer> sortList = CollUtil.sort(allMap.keySet(), Comparator.naturalOrder());
        System.out.println(sortList);
        for (Integer key : sortList) {
            System.out.println(String.format("%s : %s", key, allMap.get(key)));
            sum += allMap.get(key).get();
        }
        System.out.println(String.format("sum : %s", sum));
    }

    public static ConcurrentHashMap<Integer, AtomicInteger> initMap() {
        ConcurrentHashMap<Integer, AtomicInteger> allMap = new ConcurrentHashMap<>();
        for (int i = 0; i < 100; i++) {
            allMap.put(i, new AtomicInteger(0));
        }
        return allMap;
    }

    static class TestTask implements Runnable {
        ConcurrentHashMap<Integer, AtomicInteger> allMap;

        public TestTask(ConcurrentHashMap<Integer, AtomicInteger> allMap) {
            this.allMap = allMap;
        }

        @Override
        public void run() {
            int totalNum = 1000;
            AtomicInteger val;
            for (int i = 0; i < totalNum; i++) {
                int randomNumber = RandomUtil.randomInt(0, 100);
                val = allMap.get(randomNumber);
                if (ObjectUtil.isNull(val)) {
                    val = new AtomicInteger(0);
                    allMap.put(randomNumber, val);
                }
                val.addAndGet(1);
            }
            //System.out.println(String.format("%s -- %s", Thread.currentThread().getName(), totalNum));
        }
    }
}
